<template>
    <div class="charge-management">
        <!-- 查询条件 -->
        <el-form :inline="true" :model="queryParams" class="search-form">
            <el-form-item label="收费类型">
                <el-select v-model="queryParams.typeId" placeholder="请选择收费类型" style="width:200px;" clearable>
                    <el-option
                        v-for="type in chargeTypes"
                        :key="type.id"
                        :label="type.name"
                        :value="type.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="咨询师">
                <el-select v-model="queryParams.consultId" placeholder="请选择咨询师" style="width:200px;" clearable>
                    <el-option
                        v-for="consult in consults"
                        :key="consult.id"
                        :label="consult.name"
                        :value="consult.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
            </el-form-item>
        </el-form>

        <!-- 新增按钮 -->
        <el-button type="primary" @click="handleAdd" class="add-button">新增收费</el-button>

        <!-- 表格 -->
        <el-table :data="chargeList" style="width: 100%">
            <el-table-column prop="id" label="ID" width="100" />
            <el-table-column label="收费类型" width="200">
                <template #default="{row}">
                    {{ row.chargeType?.name || '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="chargePrice" label="收费价格" width="120" />
            <el-table-column label="咨询师" width="200">
                <template #default="{row}">
                    {{ row.consult?.name || '-' }}
                </template>
            </el-table-column>
            <el-table-column prop="countNumber" label="咨询人数" width="120" />
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button link @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button link type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination 
            style="margin-top: 20px"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[4, 8, 10, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />

        <!-- 新增/编辑弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
            <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
                <el-form-item label="收费类型" prop="typeId">
                    <el-select v-model="form.typeId" placeholder="请选择收费类型">
                        <el-option
                            v-for="type in chargeTypes"
                            :key="type.id"
                            :label="type.name"
                            :value="type.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="收费价格" prop="chargePrice">
                    <el-input v-model.number="form.chargePrice" type="number" />
                </el-form-item>
                <el-form-item label="咨询师" prop="consultId">
                    <el-select v-model="form.consultId" placeholder="请选择咨询师">
                        <el-option
                            v-for="consult in consults"
                            :key="consult.id"
                            :label="consult.name"
                            :value="consult.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="咨询人数" prop="countNumber">
                    <el-input v-model.number="form.countNumber" type="number" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 4,
    typeId: null,
    consultId: null
});

// 表格数据
const chargeList = ref([]);
const total = ref(0);

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('');

// 表单数据
const form = reactive({
    id: null,
    typeId: null,
    chargePrice: null,
    consultId: null,
    countNumber: null
});

// 表单验证规则
const rules = reactive({
    typeId: [{ required: true, message: '请选择收费类型', trigger: 'blur' }],
    chargePrice: [
        { required: true, message: '请输入收费价格', trigger: 'blur' },
        { type: 'number', message: '价格必须为数字' }
    ],
    consultId: [{ required: true, message: '请选择咨询师', trigger: 'blur' }],
    countNumber: [
        { required: true, message: '请输入咨询人数', trigger: 'blur' },
        { type: 'number', message: '人数必须为数字' }
    ]
});

const formRef = ref();

// 下拉选项数据
const chargeTypes = ref([]);
const consults = ref([]);

// 获取收费类型选项
const fetchChargeTypes = async () => {
    try {
        const res = await axios.get('/chargeType/list');
        if (res.data?.code === 1) {
            chargeTypes.value = res.data.data?.list || [];
        }
    } catch (error) {
        ElMessage.error('获取收费类型失败');
    }
};

// 获取咨询师选项
const fetchConsults = async () => {
    try {
        const res = await axios.get('/consult/selectAll');
        if (res.data?.code === 1) {
            consults.value = res.data.data?.list || [];
        }
    } catch (error) {
        ElMessage.error('获取咨询师失败');
    }
};

// 搜索
const handleSearch = async () => {
    try {
        const res = await axios.get('/charge/all', {
            params: {
                ...queryParams,
                pageNum: queryParams.pageNum,
                pageSize: queryParams.pageSize,
                typeId: queryParams.typeId,
                consultId: queryParams.consultId
            }
        });
        if (res.data?.code === 1) {
            console.log(queryParams.typeId);
            chargeList.value = res.data.data?.list || [];
            total.value = res.data.data?.total || 0;
        }
    } catch (error) {
        ElMessage.error('获取数据失败');
    }
};

// 分页大小变化
const handleSizeChange = (val) => {
    queryParams.pageSize = val;
    queryParams.pageNum = 1; // 重置为第一页
    handleSearch();
};

// 当前页变化
const handleCurrentChange = () => {
    handleSearch();
};

// 新增
const handleAdd = () => {
    dialogTitle.value = '新增收费';
    Object.assign(form, {
        id: null,
        typeId: null,
        chargePrice: null,
        consultId: null,
        countNumber: null
    });
    dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
    dialogTitle.value = '编辑收费';
    Object.assign(form, {
        id: row.id,
        typeId: row.typeId,
        chargePrice: row.chargePrice,
        consultId: row.consultId,
        countNumber: row.countNumber
    });
    dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
    try {
        await formRef.value.validate();
        const method = form.id ? 'put' : 'post';
        const url = form.id ? `/charge` : `/charge`;
        const res = await axios[method](url, form);
        if (res.data?.code === 1) {
            ElMessage.success('操作成功');
            dialogVisible.value = false;
            handleSearch();
        } else {
            ElMessage.error(res.data?.msg || '操作失败');
        }
    } catch (error) {
        if (error.response) {
            ElMessage.error(`操作失败: ${error.response.data?.msg}`);
        } else {
            ElMessage.error('网络错误');
        }
    }
};

// 删除
const handleDelete = async (id) => {
    try {
        await ElMessageBox.confirm('确认删除该记录吗？', '提示', { type: 'warning' });
        const res = await axios.delete(`/charge/${id}`);
        if (res.data?.code === 1) {
            ElMessage.success('删除成功');
            handleSearch();
        }
    } catch (error) {
        // 用户取消删除或删除失败
    }
};

// 初始化
onMounted(() => {
    fetchChargeTypes();
    fetchConsults();
    handleSearch();
});
</script>

<style scoped>
.charge-management {
    padding: 20px;
}
.search-form {
    margin-bottom: 20px;
}
.add-button {
    margin-bottom: 20px;
}
</style>